<template>
  <div class="about">
    <!-- <el-affix :offset="120"> -->
    <div class="headBox">
      <div
      
        :class="current&&item&&current.title === item.title ? 'titleBox isActive' : 'titleBox'"
        v-for="(item, index) in formInfo1"
        :key="item.title"
        @click="handleTitle(item, index)"
      >
        {{ item.title }}

        <el-icon
          style="z-index: 2"
          @click="handleDelete($event, index, current.title === formInfo1[0].title)"
        >
          <Delete />
        </el-icon>
      </div>
      <div class="titleBox" @click="handleAdd">
        <el-input
          v-if="isAdd"
          v-model="addTitle"
          type="text"
          @blur="handleAddTitle"
          :autofocus="true"
          v-focus
          ref="titleInput"
        />
        <span v-else>新增</span>
      </div>
      <el-button type="primary" @click="handleSave">导出</el-button>
      <el-button type="primary" @click="dialogImportVisible = true">导入</el-button>
      <el-button type="primary" @click="dialogAddVisible = true" :disabled="!current"
        >新增</el-button
      >
    </div>
    <!-- </el-affix> -->
    <!-- <div v-for="(item, index) in formInfo1[currentIndex]" :key="index"> -->
    <div v-if="formInfo1[currentIndex]" style="padding-top:50px">
      <h3>{{ formInfo1[currentIndex].title }}</h3>
      <div
        v-for="(item, index) in formInfo1[currentIndex].subject"
        :key="index"
        style="margin-bottom: 20px"
      >
        <div>
          题目{{ index + 1 }}：
          <el-icon style="cursor: pointer; margin-right: 10px" @click="currentQueIndex = index"
            ><EditPen
          /></el-icon>
          <el-icon style="cursor: pointer; margin-right: 10px" @click="handleQueDelete(index)">
            <Delete />
          </el-icon>
          <!-- <div><span v-html="item.question"></span></div> -->
          <prism-editor
            class="my-editor height-300"
            v-model="item.question"
            :highlight="highlighter"
            :line-numbers="false"
            :readonly="currentQueIndex !== index"
          ></prism-editor>
        </div>
        <div>
          答案：
          <prism-editor
            class="my-editor height-300"
            v-model="item.answer"
            :highlight="highlighter"
            :readonly="currentQueIndex !== index"
            :line-numbers="false"
          ></prism-editor>

          <!-- <div><span v-html="item.answer"></span></div> -->
        </div>
      </div>
    </div>
    <!-- <span v-html="formInfo1"></span> -->
    <el-dialog v-model="dialogAddVisible" title="新增题目" width="30%" :before-close="handleClose">
      <span>目录：{{ current.title }}</span>
      <div>
        题目：
        <!-- <el-input
          v-model="question"
          :autosize="{ minRows: 2 }"
          type="textarea"
          placeholder="Please input"
        /> -->
        <prism-editor
          class="my-editor height-300"
          v-model="question"
          :highlight="highlighter"
          :line-numbers="true"
        ></prism-editor>
      </div>
      <div>
        答案：
        <prism-editor
          class="my-editor height-300"
          v-model="answer"
          language="css"
          :highlight="highlighter"
          :line-numbers="true"
        ></prism-editor>

        <!-- <el-input
          v-model="answer"
          :autosize="{ minRows: 2 }"
          type="textarea"
          placeholder="Please input"
        /> -->
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleAddQuestion">提交</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog
      v-model="dialogImportVisible"
      title="导入文本"
      width="30%"
      :before-close="handleImportClose"
    >
      <div>
        文本内容：<el-input
          v-model="content"
          :autosize="{ minRows: 2 }"
          type="textarea"
          placeholder="请输入"
        />
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleImportClose">取消</el-button>
          <el-button type="primary" @click="handleImportQuestion">提交</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { Options, Vue } from "vue-class-component";
// import HelloWorld from '@/components/HelloWorld.vue'; // @ is an alias to /src
import { ref, watch } from "vue";
import { saveAs } from "file-saver"; //导出txt文档
import { toRaw } from "@vue/reactivity";
import { PrismEditor } from "vue-prism-editor";
import "vue-prism-editor/dist/prismeditor.min.css";
import { highlight, languages } from "prismjs/components/prism-core";
import "prismjs/components/prism-clike";
import "prismjs/components/prism-javascript";
import "prismjs/themes/prism-tomorrow.css";

// const vFocus = {
//   mounted: (el) => el.focus()
// }
// const checkboxGroup1 = ref(['Shanghai'])
// const cities = ['Shanghai', 'Beijing', 'Guangzhou', 'Shenzhen']
@Options({
  components: {
    // HelloWorld,
    PrismEditor,
  },
})
export default class About extends Vue {
  isAdd = 0;
  addTitle = "";
  dialogAddVisible = false;
  question = "";
  answer = "";
  formInfo = "";
  formInfo1 = [
    // {
    //   title: "Shanghai",
    //   subject: [
    //     { question: "Shanghai1", answer: "222" },
    //     { question: "Shanghai2", answer: "222" },
    //     { question: "Shanghai3", answer: "222" },
    //   ],
    // },
    // {
    //   title: "Beijing",
    //   subject: [
    //     { question: "Beijing1", answer: "222" },
    //     { question: "Beijing2", answer: "222" },
    //     { question: "Beijing3", answer: "222" },
    //   ],
    // },
    // {
    //   title: "Guangzhou",
    //   subject: [
    //     { question: "Guangzhou1", answer: "222" },
    //     { question: "Guangzhou2", answer: "222" },
    //     { question: "Guangzhou3", answer: "222" },
    //   ],
    // },
    // {
    //   title: "Shenzhen",
    //   subject: [
    //     { question: "Shenzhen1", answer: "222" },
    //     { question: "Shenzhen2", answer: "222" },
    //     { question: "Shenzhen3", answer: "222" },
    //   ],
    // },
  ];
  current = {};
  currentIndex = 0;
  currentQueIndex = "";
  content = "";
  dialogImportVisible = false;
  titleInput = ref();
  test = ref(0);
  // setup() {
  //   console.log('aaa');

  //   const titleInput = ref(null);
  //   // onMounted(() => {
  //   //   console.log(titleInput.value)
  //   // })

  //     let handleAdd = () => {
  //       // console.log('this.$refs.titleInput',getCurrentInstance())
  //       console.log("111", titleInput.value);

  //       // this.$refs.titleInput.focus()
  //       this.isAdd = 1;
  //     };

  //   return {
  //     handleAdd,
  //   };
  // }

  //  destroyWatch = watch(() => route.query, (newValue, oldValue) => {
  //   console.log('destroyWatch')
  //     data.searchInfo = {...data.searchInfo, ...newValue};
  //     data.timeArr = [Number(data.searchInfo.start_time)*1000,Number(data.searchInfo.end_time)*1000]
  //     getList()
  // }, {immediate: true, deep: true})
  // watch(count , (newValue, oldValue) => {
  //   console.log("已触发count： ", newValue);
  // });

  mounted() {
    this.formInfo1 = JSON.parse(sessionStorage.getItem("formInfo1"))
      ? JSON.parse(sessionStorage.getItem("formInfo1"))
      : this.formInfo1;
    this.current = this.formInfo1.length>0 ?this.formInfo1[0]:{};

    watch(
      () => this.formInfo1,
      (curVal, preVal) => {
        sessionStorage.setItem("formInfo1", JSON.stringify(toRaw(curVal)));
      },
      {
        immediate: true,
        deep: true, // 深度监听的参数
        //配置项
      }
    );

    // console.log('this.$refs.titleInput111',titleInput.value);
  }

  onBeforeRouteLeave(to, from) {
    // this.destroyWatch()
  }

  handleTitle(item, index) {
    this.current = item;
    this.currentIndex = index;
    this.test = index;
    this.isAdd = 0;
  }
  handleSave() {
    // var tableData = [
    //   { name: "111", title: "aaa", key: "fghjuj" },
    //   { name: "222", title: "ww", key: "fghjuasfj" },
    //   { name: "333", title: "daf", key: "fsadf" },
    // ];
    // var strr = "";
    // tableData.forEach((item) => {
    //   strr +=
    //     "ID:" + item.name + "   " + "名称:" + item.title + "   " + "年龄:" + item.key + "\r\n";
    // });
    // var allStr = "aaaa" + "\r\n" + "\r\n" + strr;

    var data = JSON.stringify(toRaw(this.formInfo1));

    let str = new Blob([data], { type: "text/plain;charset=utf-8" });
    // 注意：这里要手动写上文件的后缀名
    saveAs(str, `合集文本.docx`);
  }
  handleAdd() {
    // const titleInput = ref();
    //     console.log('this.$refs.titleInput',this.titleInput.value);

    // this.$nextTick(() => {
    //   console.log("this.$refs.titleInput1", this.titleInput);
    // });

    // this.$refs.titleInput.focus()
    this.isAdd = 1;
  }
  handleAddTitle() {
    if (this.addTitle) {
      var temp = { title: this.addTitle, subject: [] };
      this.current = this.formInfo1.length === 0 ? temp : this.current;
      this.formInfo1.push(temp);
      this.addTitle = "";
    }

    this.isAdd = 0;
  }
  handleDelete(event, index, flag) {
    event.stopPropagation();
    // arr.some(item => item === val);
    // var temp= this.formInfo1.findIndex(itemm => itemm.title===item)
    this.formInfo1.splice(index, 1);
    this.current = flag || this.currentIndex === index ? this.formInfo1[0] : this.current;

    var temp = this.formInfo1.findIndex((itemm) => itemm.title === this.current["title"]);
    this.currentIndex = temp;
    // console.log('temp',temp);
  }
  handleQueDelete(index) {
    this.formInfo1[this.currentIndex].subject.splice(index, 1);
  }
  handleClose() {
    this.dialogAddVisible = false;
    this.question = "";
    this.answer = "";
  }
  handleImportClose() {
    this.dialogImportVisible = false;
    this.content = "";
  }
  handleAddQuestion() {
    // var temp = {
    //   question: this.question.replace(/\n/g, "<br/>").replace(/\s/g, " "),
    //   answer: this.answer.replace(/\n/g, "<br/>").replace(/\s/g, " "),
    // };
    var temp = {
      question: this.question,
      answer: this.answer,
    };

    this.formInfo1[this.currentIndex].subject.push(temp);
    this.dialogAddVisible = false;
    this.question = "";
    this.answer = "";

    // this.question.replace(/\n/g, "<br/>)".replace(/\s/g, " ")
  }
  handleImportQuestion() {
    // this.formInfo = this.content.replace(/\n/g, "<br/>").replace(/\s/g, " ");
    // this.formInfo1 = JSON.parse(this.content.replace(/\n/g, "<br/>").replace(/\s/g, " "));
    this.formInfo1 = JSON.parse(this.content);
    this.current = this.formInfo1[0];
    this.currentIndex = 0;
    // .replace(/\n/g, “<br/>”).replace(/\s/g, “ ”)
    this.dialogImportVisible = false;
  }
  highlighter(code) {
    return highlight(code, languages.js); //returns html
  }
  //   encodeHtml(str){
  //   var encodedStr = "" ;
  //   if (str=="") return encodedStr ;
  //   else {
  //     for (var i = 0 ; i < str.length ; i ++){
  //       encodedStr += "&#" + str.substring(i, i + 1).charCodeAt().toString(10) + ";" ;
  //     }
  //   }
  //   return encodedStr ;
  // }

  // increase() {
  // }
  // get doubleCount(): number {
  //   return this.count * 2;
  // }
}
</script>
<style scoped lang="scss">
.headBox {
  position: fixed;
  width:calc(100% - 500px);
  background: #fff;
  height: 50px;
  z-index: 2;
  display: flex;
  justify-content: center;
  align-items: center;
  .el-button {
    margin-left: 10px;
  }
}
.titleBox {

  // width: auto;
  width: -webkit-fill-available;
  padding: 0 10px;
  height: 30px;
  border: 1px solid #555;
  display: flex;
  justify-content: center;
  align-items: center;
}

.isActive {
  color: #fff;
  // border-color:#fff;
  background: #409eff;
}
.my-editor {
  background: #efefef ;
  color: #2d2d2d;
  font-family: Fira code, Fira Mono, Consolas, Menlo, Courier, monospace;
  font-size: 14px;
  line-height: 1.5;
  padding: 5px;
}
/* optional */
.prism-editor__textarea:focus {
  outline: none;
}
/* not required: */
.height-300 {
  height: auto;
}
</style>
